package com.mall.live.service.impl;

import com.mall.live.mapper.LiveFollowerMapper;
import com.mall.live.service.ILiveFollowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LiveFollowerServiceImpl implements ILiveFollowerService {

    @Autowired
    private LiveFollowerMapper liveFollowerMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 关注主播
     * @param id
     * @param uid
     * @param image
     */
    @Override
    public void attention(Long id, Long uid,String image) {
        liveFollowerMapper.attention(id,uid,image);
    }

    /**
     * 点赞
     * @param id
     */
    @Override
    public void like(Long id,Integer num) {
        Integer likeNum;
        //获得redis里面的点赞数
        likeNum = (Integer)redisTemplate.boundHashOps("like").get(id);
        if(likeNum==null){
            //获得点赞数
            likeNum=liveFollowerMapper.likeNum(id);
            likeNum=likeNum+1;
            //存入redis
            redisTemplate.boundHashOps("like").put(id,likeNum);
        }else {
            likeNum=likeNum+1;
            redisTemplate.boundHashOps("like").put(id,likeNum);
        }
    }

    /**
     * 定时器，每隔五分钟获取点赞数，修改
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void  updateLikeNum(){
        HashMap<Long,Integer> like = (HashMap)redisTemplate.boundHashOps("like").entries();
            //遍历获得键，值，去数据库修改
            for(Map.Entry<Long,Integer> map : like.entrySet()){
                liveFollowerMapper.like(map.getKey(),map.getValue());
            }
    }
}
